<template>
  <div class="layout-col flex5 bss ml16">
    <div class="ww100 flex-bc plr12 ptb8 bs4">
      <div class="flex-sc">
        <span class="f15 fw">{{isNull(publicStore.active)?'':publicStore.active.role_name + '配置功能'}}</span>
      </div>
      <div class="flex-ec flex1 h30">
        <el-form class="ww100 flex-ec" :model="state.from" label-width="115px">
          <div class="rad4 ptb6 plr10 flex-cc cursor bgi3 white ml10" @click.stop="handleSubmit(formRef)">
            <i-ep-plus class="f12 fw" /><span class="f14 ml2">保存</span>
          </div>
        </el-form>
      </div>
    </div>
    <div class="flex1 overlay ww100 flex-col-ss">
      <el-tree 
        :data="state.tree" 
        :props="defaultProps" 
        :default-expand-all="true"
        ref="treeRef"
        class="ww100"
        node-key="code"
        accordion 
        highlight-current
        empty-text="暂无数据"
        show-checkbox>
        <template #default="{ node, data }">
          <span class="flex-bc">
            <span>{{ node.label }}</span>
          </span>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import api from '@/api'
	const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  const configStore = proxy.configStore()
  const state = reactive({
	  ...publicStore.$state,
    pointsTree: [],
    existList: [],
    allList: [],
  })
  let exposeRef = $ref()
  let treeRef = $ref()
  let tree = $ref([])
  let defaultKeys = $ref()
  const defaultProps = {
    children: 'children',
    label: 'name',
  }

  watch(() => publicStore.active, async(val) => {
    await nextTick()
    if(proxy.isNull(val)) return
    init()
  }, {immediate: false, deep: true})

  const init = async(key) => {
    state.pointsTree = []
    state.existList = []
    state.allList = []
    let query1 = {"o": "o_comm_role_func", "p":[publicStore.active.id]}
    let query2 = {"o": "o_comm_sys_role_func", "p": ["0"]}
    state.params = {queryApi1: query1, queryApi2: query2}
    state.list = await publicStore.post(state.params)
    state.list.queryApi2.forEach(item => {
      if(item.is_exist == '1'){
        let exist = state.list.queryApi1.find(a=>a.code == item.code)
        if(exist){
          state.pointsTree.push(exist)
          if(exist.is_exist == '1'){
            state.allList.push(exist)
            if(exist.up_code == '0' || exist.up_code == ''){
              let child = state.list.queryApi1.filter(a=>a.up_code == exist.code && a.is_exist == '0')
              if(child.length == 0){
                state.existList.push(exist.code)
              }
            }else{
              state.existList.push(exist.code)
            }
          }
        }
      }
    })
    state.tree = proxy.treeData(state.pointsTree, 'code', 'up_code', 'children')
    treeRef.setCheckedKeys(state.existList, false)
  }

  const handleSubmit = (formEl) => {
    state.allList = state.list.queryApi1.filter(a=>a.is_exist == '1')
    console.log('allList', state.allList)
    let addList = []
    let delList = []
    let list = treeRef.getCheckedKeys(false)
    list.forEach((item,index) => {
      let exist = state.allList.find(a => { return a.code == item})
      if(!exist){
        let json = {o: "o_comm_role_func", t: "add", a: "添加", role_id: publicStore.active.id, func_code: item, id: parseInt(new Date().getTime()+index)}
        addList.push(json)
      }
    })
    state.allList.forEach(item => {
      let json = {o: "o_comm_role_func", t: "del", a: "删除", i: 0, id: item.id}
      if(item.up_code == '0' || item.up_code == ''){
        let child = state.pointsTree.filter(a=>a.up_code == item.code)
        let status = false
        list.forEach(item => {
          let value = child.find(a=>a.code == item)
          if(value){
            status = true
          }
        })
        if(!status){
          delList.push(json)
        }
      }else{
        let exist = list.find(a => { return a == item.code })
        if(!exist){
          delList.push(json)
        }
      }
    })
    console.log('allQuery', addList, delList)
    let allQuery = Object.assign(addList, delList)
    if(allQuery.length == 0) return 
    api.updateApi(allQuery).then(res => {
      if(res.errcode == 0){
        ElNotification({ title: '提示', message: '操作成功', type: 'success' })
        init()
      }
    }).catch((err) => {
        ElNotification({ title: '提示', message: '操作失败', type: 'error' })
    })
  }
</script>
  
<style scoped lang="scss">

</style>
  